package com.merge.sample.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.merge.sample.model.MData;
import com.merge.sample.model.RData;

public class MyUtil {
	public static final String ln = System.getProperty("line.separator");

	public static String[] listFile(String folder) {
		File file = new File(folder);
		return file.list();
	}

	public static List<String> checkConflictFiles(String sourcefolder,
			String targetfolder, MData data) {
		List<String> rt = new ArrayList<String>();
		String[] sourceFiles = listFile(sourcefolder);
		String[] targetFiles = listFile(targetfolder);
		if (sourceFiles == null || targetFiles == null) {
			return rt;
		}
		Set<String> set = new HashSet<String>();
		for (String s : sourceFiles) {
			if (!data.isIgnore(s))
				set.add(s);
		}
		for (String s : targetFiles) {
			if (set.contains(s)) {
				rt.add(s);
			}
		}
		return rt;
	}

	public static int copyFiles(String sourceFolder, String targetFolder,
			Set<String> ignoreList) throws IOException {
		int rt = 0;
		String[] sourceFiles = listFile(sourceFolder);
		resolvePath(targetFolder, false);
		for (String fn : sourceFiles) {
			if (ignoreList.contains(fn))
				continue;
			copyFile(formatFilename(sourceFolder, fn),
					formatFilename(targetFolder, fn));
			rt++;
		}
		return rt;
	}

	public static String formatFilename(String folder, String fn) {
		String rt = folder;
		if (!rt.matches("^.+[\\\\/]$")) {
			rt += File.separator;
		}
		if (fn.matches("^[\\\\/].+$")) {
			fn = fn.substring(1);
		}
		rt += fn;
		return rt;
	}

	// D:\workspace_android\MergeProject\res\drawable\right_selector.xml
	static Pattern pPath = Pattern
			.compile("^([^\\\\/]*(?:[\\\\/][^\\\\/]+)*)[\\\\/]([^\\\\/]+)$");

	public static void resolvePath(String path, boolean filePath) {
		List<String> pl = new ArrayList<String>();
		File tmp = new File(path);
		while (!tmp.exists()) {
			Matcher m = pPath.matcher(path);
			if (m.find()) {
				path = m.group(1);
				tmp = new File(path);
				pl.add(m.group(2));
			}
		}
		int begin = filePath ? 1 : 0;
		for (int i = pl.size() - 1; i >= begin; i--) {
			path = path + File.separator + pl.get(i);
			new File(path).mkdir();
		}
	}

	public static void resolvePath(String path) {
		resolvePath(path, true);
	}

	public static void main(String[] args) {
		String path = "c:\\workspace_android\\MergeProject\\res\\drawable\\right_selector.xml";
		resolvePath(path);
	}

	public static void copyFile(String sf, String tf) throws IOException {
		File sourceFile = new File(sf);
		File targetFile = new File(tf);
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			outBuff.flush();
		} finally {
			if (inBuff != null)
				inBuff.close();
			if (outBuff != null)
				outBuff.close();
		}
	}

	public static String dealWithSource(File file, List<RData> datas) {
		StringBuilder rt = new StringBuilder();
		Map<Integer, Integer> comment = new HashMap<Integer, Integer>();
		for (RData d : datas) {
			if (d.type == RData.TYPE_VALUES) {
				continue;
			}
			if (d.startline == d.endline) {
				comment.put(d.startline, 3);
			} else {
				comment.put(d.startline, 1);
				comment.put(d.endline, 2);
			}
		}
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			while ((tempString = reader.readLine()) != null) {
				if (comment.containsKey(line)) {
					switch (comment.get(line)) {
					case 1:
						tempString = String.format("<!-- %s", tempString);
						break;
					case 2:
						tempString = String.format("%s -->", tempString);
						break;
					case 3:
						tempString = String.format("<!-- %s -->", tempString);
						break;
					}
				}
				rt.append(tempString).append(ln);
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return rt.toString();
	}

	public static String getFileContent(File file) throws Exception {
		FileInputStream in = new FileInputStream(file);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] temp = new byte[1024];

		int size = 0;
		while ((size = in.read(temp)) != -1) {
			out.write(temp, 0, size);
		}
		in.close();
		return out.toString();
	}

	public static String getFileContent(String fn) throws Exception {
		return getFileContent(new File(fn));
	}

	public static void writeStringToFile(String fileName, String content) {
		byte[] bytes = null;
		try {
			bytes = content.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			return;
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(fileName, false);
			fos.write(bytes);
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException iex) {
			}
		}
	}

//	public static boolean writeStringToFile(String fileName, String content) {
//		File file = new File(fileName);
//		try {
//			OutputStreamWriter os = null;
//			os = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
//			os.write(content);
//			os.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//			return false;
//		}
//		return true;
//	}

}
